<?php
namespace app\center\controller;
use app\center\logic\CopyMyLogic;

/**
 * 抄送给我api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/10/09
 * Time: 15:12
 */
class CopyMy extends Base {

    public function __construct(){
        parent::__construct();
        $this->cm_logic = new CopyMyLogic();
    }

    /**
     * 获取抄送给我
     * @return \think\response\Json
     */
    public function ajax_get_cm(){
        $params = input();
        $r = $this->check_user_token($params);
        if($r['code'] != 1){
            return json($r);
        }

        //检查用户规则
        $r = $this->cm_logic->check_user_rule();
        if($r['code'] != 1){
            return json($r);
        }
        $u_detail = $r['data']['detail'];

        $maps = $this->cm_logic->get_search_cm_maps($u_detail['openid'],$params['from_openid'],$params['source'],$params['start_time']);
        $limit = ($params['page'] - 1) * $params['rows'];

        $list = model('copy')->get_list($maps,'id,from_openid,source,name,status,is_read,c_time','is_read asc,id desc','',$limit,$params['rows']);
        foreach($list as $k => $v){
            //查找用户
            $u_maps = [];
            $u_maps[] = ['openid','=',$v['from_openid']];
            $u_detail = model('user')->get_detail($u_maps,'id,username');

            $content = '抄送人：' . $u_detail['username'];
            $list[$k]['content'] = $content;
        }

        $data['list'] = $list;
        $data['total_num'] = 0;
        $data['page'] = $params['page'];
        return json($this->cm_logic->get_response(1,'OK',$data));
    }

    /**
     * 处理抄送给我
     * @return \think\response\Json
     */
    public function ajax_deal_cm(){
        $params = input();
        $r = $this->check_user_token($params);
        if($r['code'] != 1){
            return json($r);
        }

        //检查用户规则
        $r = $this->cm_logic->check_user_rule();
        if($r['code'] != 1){
            return json($r);
        }
        $u_detail = $r['data']['detail'];

        //检查处理抄送给我规则
        $r = $this->cm_logic->check_deal_cm_rule($u_detail['openid'],$params);
        if(!$r['code']){
            return json($r);
        }
        $c_detail = $r['data']['c_detail'];

        $c_data = [];
        $c_data['explain'] = trim($params['explain']);
        $c_data['reply_time'] = date('Y-m-d H:i:s');

        $maps = [];
        $maps[] = ['id','=',$c_detail['id']];
        $r = model('copy')->force()->save($c_data,$maps);
        if($r !== false){
            //更新批复抄送积分
            $si = new \app\common\controller\SaveIntegral();
            $r = $si->save_rc_integral($c_detail['id']);

            //发送批复消息
            $c = new \app\common\controller\Copy();
            $r = $c->send_reply_msg($c_detail['id']);

            return json($this->cm_logic->get_response(1,'保存成功'));
        }
        return json($this->cm_logic->get_response(0,'保存失败'));
    }
}
